package com.news.reader;

import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;

import org.apache.commons.net.nntp.Article;
import org.apache.commons.net.nntp.NNTPClient;
import org.apache.commons.net.nntp.NewsgroupInfo;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ThreadList extends ListActivity  {
	private NNTPClient client;
	private ArrayList<String> subjects = new ArrayList<String>();
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Bundle extras = getIntent().getExtras();
        if(extras !=null)
        {
        	try {
        		ProgressDialog MyDialog = ProgressDialog.show(ThreadList.this, "Loading Threads" , " Loading. Please wait ... ", true);
        		client = new NNTPClient();
				client.connect(extras.getString("newsgroup"), 119);
        		NewsgroupInfo group = new NewsgroupInfo();
        		//client.selectNewsgroup(extras.getString("group"), group);
        		client.selectNewsgroup("newsgroup.hkland.tsimshatsui", group);
    			int highArticleNumber = group.getLastArticle();
    			int lowArticleNumber = highArticleNumber - 100;
    			Article[] articles = NNTPUtils.getArticleInfo(client, lowArticleNumber, highArticleNumber);
    			for (int i = 0; i < articles.length; i++) {
    				subjects.add(NNTPUtils.getASCIIToBig5String(articles[i].getSubject()));
    				//Subjects.add(NNTPUtils.getASCIIToBig5String(articles[i].simplifiedSubject()));
    			}

	            setListAdapter(new ArrayAdapter<String>(this, R.layout.row, R.id.label, subjects));
	            MyDialog.dismiss();
			} catch (SocketException e) {
				e.printStackTrace();
			} catch (IOException e) {
				//Toast t = Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG);
				//t.show();
				e.printStackTrace();
			} finally {
	            try {
	                if (client.isConnected())
	                    client.disconnect();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
			}
        }
    }
    
    public void onListItemClick(ListView parent, View v, int position, long id) {
    	//launchThreadList(groups.get(position));
    	finish();
    }
    

    
}
